package io.oschina.binv.kapp.framework

import android.content.Intent
import android.os.Bundle
import android.support.v4.app.Fragment
import io.oschina.binv.kapp.R
import io.oschina.binv.kapp.framework.extend.printOrReport
import io.oschina.binv.kapp.framework.widget.video.JCVideoPlayer
import io.reactivex.functions.Consumer
import kotlin.properties.Delegates

class ReuseActivity : BaseActivity() {
    var fragmentName:String by Delegates.notNull()
    var fragmentArgs:Bundle by Delegates.notNull()
    companion object {
        val FRAGMENT_NAME = "FragmentName"
        val FRAGMENT_ARGS = "FragmentArgs"
    }

    init {
        //必须放置此处,否则因为用户操作,或androi生命周期原因会多次执行,导致内存泄露(DESTROY后,才会销毁)
        RxBus.toObservable(FinishEvent::class.java)
                .compose(ioToMain())
                .subscribe(Consumer {
                    data->
                    Log.i("this.fragmentName="+fragmentName+",data="+data.toString())
                    if(data.canonicalName==this::class.java.canonicalName && data.args==fragmentName){
                        finish()
                    }
                },Consumer {
                    ex->this.printOrReport(ex)
                })
    }

    override fun setContentView() {
        setContentView(R.layout.framework_activity_reuse)
    }

    override fun onBackPressed() {
        if (JCVideoPlayer.backPress()) {
            return
        }
        super.onBackPressed()
    }

    override fun initViewsAndLocalData(savedIntent: Intent): (outIntent: Intent) -> Unit {
        fragmentName = savedIntent.getStringExtra(FRAGMENT_NAME)
        fragmentArgs = savedIntent.getBundleExtra(FRAGMENT_ARGS)
        try {
            val fragmentClass = Class.forName(fragmentName)
            val existFragment = supportFragmentManager.findFragmentById(R.id.fl_fragmentContainer)
            if (existFragment == null || existFragment::class.java!=fragmentClass) {
                val fragmentInstance= fragmentClass.newInstance()
                if(fragmentInstance!=null){
                    if(fragmentInstance is Fragment){
                        fragmentInstance.arguments=fragmentArgs
                        supportFragmentManager
                                .beginTransaction()
                                .replace(R.id.fl_fragmentContainer,fragmentInstance)
                                .commitAllowingStateLoss();
                    } else {
                        throw Exception("$fragmentName is not a Fragment")
                    }
                }else{
                    throw Exception("$fragmentName must have Non-parametric Constructors")
                }
            }
        }catch (ex:Throwable){
            this.printOrReport(ex)
        }
        return { outIntent->
            //外部,传递值,未变化的可不更新
            //outIntent.putExtra(FRAGMENT_NAME,fragmentName)
            //outIntent.putExtra(FRAGMENT_ARGS,fragmentArgs)
        }
    }

    override fun loadRemoteData() {

    }
}
